<template>
  <div v-show="isShow">
    <div id="wrap" class="wrap">
      <div id="control" class="operation">
        <!-- 操作功能，下面三个，先注释上 -->
        <div id="canvas-color" class="operation-item brush" v-show="false">
          <span>画笔</span>
          <ul>
            <li style="background: #fef4ac"></li>
            <li style="background: #0018ba"></li>
            <li style="background: #ffc200"></li>
            <li style="background: #f32f15"></li>
            <li style="background: #cccccc"></li>
            <li style="background: #5ab639"></li>
          </ul>
        </div>
        <div id="canvas-brush" v-show="false">
          <h5>画笔大小</h5>
          <span class="small-brush"></span>
          <span class="middle-brush"></span>
          <span class="big-brush"></span>
        </div>
        <div id="canvas-control" class="operation-item back" v-show="false">
          <span>操作</span>
          <span title="撤回" class="return-control"></span>
          <span title="还原" class="next-control"></span>
          <span title="清除" class="empty-control"></span>
        </div>
        <div id="canvas-drawImage" class="operation-item btn">
          <button style="border: 1px solid #0063e6;color: #0063e6;" class="drawImage" @click="addWk()">生成工单</button>
          <button style="border: 1px solid #0063e6;color: #0063e6;" class="uploadImage" @click="upload()">上传图片</button>
          <button style="border: 1px solid #0063e6;color: #0063e6;" class="close" @click="closeCvs()">关闭</button>
          <!-- <button id="next" style="border: 1px solid #0063e6;color: #0063e6;" class="close">下一步</button>
          <button id="pre" style="border: 1px solid #0063e6;color: #0063e6;" class="close">上一步</button> -->
        </div>
      </div>

      <canvas id="canvas" class="my-canvas" width="600" height="400"></canvas>

    </div>
    <div id="imgDiv"></div>
  </div>
</template>

<script>
import { uploadVideobase64 } from '@/api/video.js'
export default {
  data() {
    return {
      ctx: null,
      my_canvas: null,
      isShow: false,   // 是否展示截图的面板
      is_addwk: false,
      // 缓存画布
      cacheCanvas: null
    };
  },
  props: {
    cvsData: {
      // type: Object,
      default: () => { return {} }
    },
    // isShow: {
    //   type: Boolean,
    //   default: false
    // },
    device_id: {
      type: [Number, String],
      default: ''
    },
  },

  watch: {
    cvsData(newData, oldData) {
      console.log("旧画布截图：", oldData, "新画布截图：", newData);
      if (newData !== null) {
        this.my_canvas._initImage(this.ctx);
      }
    },
  },
  mounted() {
    var that = this
    const doc = document
    let canvas = doc.getElementById("canvas")
    let colorDiv = doc.getElementById("canvas-color")
    let brushDiv = doc.getElementById("canvas-brush")
    let controlDiv = doc.getElementById("canvas-control")
    let drawImageDiv = doc.getElementById("canvas-drawImage")
    let imgDiv = doc.getElementById("imgDiv")

    function Canvas() {   // 构造器
      this.init.apply(this, arguments);
    }

    Canvas.prototype = {   // 原型链类属性和类方法
      //存储当前表面状态数组-上一步
      preDrawAry: [],
      //存储当前表面状态数组-下一步
      nextDrawAry: [],
      //中间数组
      middleAry: [],
      //配置参数
      confing: {
        lineWidth: 1,
        lineColor: "red",
        shadowBlur: 2
      },
      init(oCanvas, oColor, oBrush, oControl, oDrawImage, imgDiv) {
        this.canvas = oCanvas;
        var ctx = (that.ctx = this.context = oCanvas.getContext("2d"));

        this._initImage(ctx);
        this.colorDiv = oColor;
        this.brushDiv = oBrush;
        this.controlDiv = oControl;
        this.drawImageDiv = oDrawImage;
        this.imgDiv = imgDiv;
        this._initDraw();
        this._draw(oCanvas);
        this.setColor();
        this.setBrush();
        this.preClick();
        this.nextClick();
        this.clearClick();
        this.drawImage(oCanvas);
      },
      _initImage(ctx) {   // 画布 初始化图片
        console.log("查看图片资源：",that.cvsData);
        if (that.cvsData !== null) {
          var canvas = document.getElementById("canvas")
          console.log('宽 :>> ', canvas.style.width.replace("px", ""))
          console.log('高 :>> ', canvas.style.height.replace("px", ""))

          canvas.width = canvas.style.width.replace("px", "")
          canvas.height = canvas.style.height.replace("px", "")

          console.log("画布宽高度：", canvas.width, canvas.height);
          ctx.drawImage(that.cvsData, 0, 0, canvas.width, canvas.height);
        }
        /** 加载图片start */
        // var img = new Image();
        // img.onload = function () {
        //     ctx.drawImage(img, 0, 0);
        // }
        // img.src = "/imgs/bigdata.png";
        /** 加载图片end */
      },
      _initDraw() {
        var preData = this.context.getImageData(0, 0, 600, 400);
        //空绘图表面进栈
        this.middleAry.push(preData);
      },
      // 涂鸦主程序
      _draw(oCanvas, context) {
        var flag = false;
        var _this = this;
        // oCanvas.parentNode.onmousedown = function(e){
        //     console.log("画布父级对象：",e);
        // }
        oCanvas.onmousedown = function(e) {
          console.log(
            "oCanvas.parentNode:",
            oCanvas.parentNode.scrollLeft,
            oCanvas.parentNode.scrollTop
          );

          flag = true;
          console.log("onmousedown:", e);
          // let x = e.clientX-54
          // let y = e.clientY-20
          let x = e.pageX - 54
          let y = e.pageY - 35
          let left = this.parentNode.offsetLeft
          let top = this.parentNode.offsetTop
          let canvasX = x - left
          let canvasY = y - top

          console.log(y, this.parentNode, this.parentNode.offsetTop, canvasY);

          _this._setCanvasStyle();
          //清除子路径
          _this.context.beginPath();
          _this.context.moveTo(canvasX, canvasY);
          //当前绘图表面状态
          var preData = _this.context.getImageData(0, 0, 600, 400);
          //当前绘图表面进栈
          _this.preDrawAry.push(preData);
          document.onmousemove = function(e) {
            // console.log("onmousemove:", e);
            if (flag) {
              var x2 = e.pageX,
                y2 = e.pageY,
                t = e.target,
                canvasX2 = x2 - left-54,
                canvasY2 = y2 - top-35;
              // console.log("计算后的点：", canvasX2, canvasY2);
              if (t == oCanvas) {
                _this.context.lineTo(canvasX2, canvasY2);
                _this.context.stroke();
              } 
              else {
                _this.context.beginPath();
              }
            }
            return;
          };
          document.onmouseup = function(e) {
            flag = false;
            var t = e.target;
            if (t == oCanvas) {
              //当前绘图表面状态
              var preData = _this.context.getImageData(0, 0, 600, 400);
              if (_this.nextDrawAry.length == 0) {
                //当前绘图表面进栈
                _this.middleAry.push(preData);
              } else {
                _this.middleAry = [];
                _this.middleAry = _this.middleAry.concat(_this.preDrawAry);
                _this.middleAry.push(preData);
                _this.nextDrawAry = [];
                $(".js-next-control").addClass("next-control");
                $(".next-control").removeClass("js-next-control");
              }

              _this._isDraw();
            }
            this.onmousemove = null;
          };
        };
        oCanvas.onmouseup = function() {
          flag = false;
          // console.log("onmouseup:", flag);
        };
      },
      // 设置画笔
      _setCanvasStyle() {
        this.context.lineWidth = this.confing.lineWidth;
        this.context.shadowBlur = this.confing.shadowBlur;
        this.context.shadowColor = this.confing.lineColor;
        this.context.strokeStyle = this.confing.lineColor;
      },
      // 设置颜色
      setColor() {
        this.colorDiv.onclick = this.bind(this, this._setColor);
      },
      _setColor(e) {
        var t = e.target;
        console.log('画笔颜色 :>> ', t);
        if (t.nodeName.toLowerCase() == "li") {
          this.confing.lineColor = t.style.backgroundColor;
          $(".js-border-color").removeClass("js-border-color");
          $(t).addClass("js-border-color");
        }
      },
      // 设置画笔大小
      setBrush() {
        this.brushDiv.onclick = this.bind(this, this._setBrush);
      },
      _setBrush(e) {
        var t = e.target;
        if (t.nodeName.toLowerCase() == "span") {
          if (t.className.indexOf("small-brush") >= 0) {
            this.confing.lineWidth = 3;
          } else if (t.className.indexOf("middle-brush") >= 0) {
            this.confing.lineWidth = 6;
          } else if (t.className.indexOf("big-brush") >= 0) {
            this.confing.lineWidth = 12;
          }
          $(".js-bg-color").removeClass("js-bg-color");
          $(t).addClass("js-bg-color");
        }
      },
      // 判断是否已涂鸦,修改按钮状态
      _isDraw() {
        if (this.preDrawAry.length) {
          // $('.return-control').addClass('js-return-control');
          // $('.return-control').removeClass('return-control');
          // $('.empty-control').addClass('js-empty-control');
          // $('.empty-control').removeClass('empty-control');
        } 
        else {
          return false;
        }
      },
      // 点击上一步-改变涂鸦当前状态
      preClick() {
        var pre = this.controlDiv.getElementsByTagName("span")[0];
        // var pre = document.getElementById("pre")
        pre.onclick = this.bind(this, this._preClick);
        console.log('上一步事件拿的的是什么 :>> ', pre)
      },
      _preClick() {
        if (this.preDrawAry.length > 0) {
          var popData = this.preDrawAry.pop();
          var midData = this.middleAry[this.preDrawAry.length + 1];
          this.nextDrawAry.push(midData);
          this.context.putImageData(popData, 0, 0);
        }
        if (this.nextDrawAry.length) {
          // $('.next-control').addClass('js-next-control');
          // $('.next-control').removeClass('next-control');
        }
        if (this.preDrawAry.length == 0) {
          // $('.js-return-control').addClass('return-control');
          // $('.return-control').removeClass('js-return-control');
        }
      },
      // 点击下一步-改变涂鸦当前状态
      nextClick() {
        var next = this.controlDiv.getElementsByTagName("span")[1];
        // var next = document.getElementById("next")
        next.onclick = this.bind(this, this._nextClick);
        console.log('下一步事件拿的的是什么 :>> ', next)
      },
      _nextClick() {
        if (this.nextDrawAry.length) {
          var popData = this.nextDrawAry.pop();
          var midData = this.middleAry[
            this.middleAry.length - this.nextDrawAry.length - 2
          ];
          this.preDrawAry.push(midData);
          this.context.putImageData(popData, 0, 0);
        }
        if (this.preDrawAry.length) {
          // $('.return-control').addClass('js-return-control');
          // $('.return-control').removeClass('return-control');
        }

        if (this.nextDrawAry.length == 0) {
          // $('.js-next-control').addClass('next-control');
          // $('.next-control').removeClass('js-next-control');
        }
      },
      // 清空
      clearClick() {
        var clear = this.controlDiv.getElementsByTagName("span")[2];
        clear.onclick = this.bind(this, this._clearClick);
      },
      _clearClick() {
        var data = this.middleAry[0];
        this.context.clearRect(
          0,
          0,
          this.context.canvas.width,
          this.context.canvas.height
        );
        this.preDrawAry = [];
        this.nextDrawAry = [];
        this.middleAry = [this.middleAry[0]];
        this._initImage(this.context);
        // this.controlDiv.getElementsByTagName("span")[0].className = "return-control";
        // this.controlDiv.getElementsByTagName("span")[1].className = "next-control";
        // this.controlDiv.getElementsByTagName("span")[2].className = "empty-control";
      },
      //生成图像
      drawImage() {
        var btn = this.drawImageDiv.getElementsByTagName("button")[0];
        btn.onclick = this.bind(this, this._drawImage);
      },
      _drawImage() {
        var url = this.canvas.toDataURL("image/png");
        // img = new Image();
        // img.src = url;
        console.log("图像base64:",url);
        return url;
        // this.imgDiv.innerHTML = "";
        // this.imgDiv.appendChild(img);
      },
      bind(obj, handler) {
        return function() {
          return handler.apply(obj, arguments);
        };
      }
    }

    this.my_canvas = new Canvas(
      canvas,
      colorDiv,
      brushDiv,
      controlDiv,
      drawImageDiv,
      imgDiv
    )
  },
  methods: {
    // 上传图片到下载中心
    upload() {
      var baseurl = this.my_canvas._drawImage();
      console.log("画布对象:",baseurl);

      let arr1 = [];
      arr1.push({"deviceId":this.device_id, "channelId": this.channel_id, "pictureBase64Data": baseurl});
      uploadVideobase64(arr1).then(res => {
        console.log("图片上传结果:",res);
      }).catch()
    },
    // 创建单个工单
    addWk() {
      let url = this.my_canvas._drawImage()
      this.$emit('add_workorder', url)
      this.isShow = false;
    },
    //
    openCvs(){
      this.isShow = true;
    },
    closeCvs(){
      this.isShow = false;
    },
    // 下面的是废用的方法
    quadraticSnapshot() {
      var canvas = document.getElementById("canvas")
      canvas.width = canvas.style.width.replace("px", "")
      canvas.height = canvas.style.height.replace("px", "")
      this.ctx.drawImage(this.cvsData, 0, 0, canvas.width, canvas.height)

      console.log('开始缓存 :>> ')
      var image = new Image()
	    image.src = canvas.toDataURL("image/png")
      this.cacheCanvas = image.src
      console.log('完成缓存 :>> ')
    },
    multiGraphAssignment() {
      console.log('开始批量抓图片 :>> ')
      // var canvas = document.getElementById("canvas")
      // var image = new Image()
	    // image.src = canvas.toDataURL("image/png")
      // console.log('抓到的图片 :>> ', image.src)
    },
    deletePicture(){
      // this.ctx.drawImage(this.cvsData, 0, 0, canvas.width, canvas.height)
      
      // var img = new Image()
	    // img.src = this.cacheCanvas
      // let myCanvas = document.getElementById("canvas").getContext('2d')
      // console.log('重新赋值新画布 :>> ')
      // this.ctx.drawImage(img, 0, 0, canvas.width, canvas.height)

      // img.onload = () => {
      //   console.log('重新赋值新画布 :>> ')
			// 	myCanvas.drawImage(img, 0, 0)
			// }

      this.isShow = false;
    }
  }
};
</script>

<style lang="scss" scoped>
$theme_text: #0f8bfd;
$backg: rgba(0, 0, 0, 0);
$deep_text: #5e5e5e;

$border_color: #d4d4d4;
$border_light: #d9dada;
$theme: #00805a;
$theme_bg: #2b303b;
$text_light: #9fa1a2;
$text_middle: #c0c0c0;
$text_dark: #2b303b;
$obj_white: #ffffff;

// html,
// body,
// canvas,
// div,
// ul,
// li,
// h5,
// p {
//   background: #fff;
//   margin: 0;
//   padding: 0;
//   -moz-user-select: none;
//   -webkit-user-select: none;
// }
// img {
//   border: 1px #ccc solid;
// }

ul,
li {
  list-style: none;
}

.wrap {
  // width: 76%;
  // height: 74%;
  // width: 740px;
  // margin: 20px auto 5px;
  // border : 1px #ccc solid;
  // min-width: 600px;
  // min-height: 300px;
  border: solid 2px #fff;
  position: absolute;
  // top: 0px;
  z-index: 3;
  margin: 0;
  overflow: hidden;
  // transform: scale(1.5);
}

#canvas {
  // border-right: 1px #ccc solid;
  cursor: crosshair;
}

.operation {
  // background-color: #f00;
  .operation-item{
    span {
      color: #333;
      margin-right: 5px;
    }
    ul {
      background-color: blueviolet;
      display: inline-block;
      padding: 0;
      &>li {
        display: inline-block;
        margin-right: 5px;
        width: 16px;
        height: 16px;
        border: 2px solid #eeeeee;
        cursor: pointer;
      }
      
    }
  }
  .btn {
    background-color: #f5f7f5;
    padding: 5px;
    button {
      cursor: pointer;
      border: 1px solid $theme;
      color: $theme;
      background-color: rgba($color: #000000, $alpha: 0);
      font-size: 12px;
      padding: 4px 8px;
      margin-right: 5px;
    }
    .close { float: right; }
  }
}

.my-canvas{
  width: 100%;
  height: 93%;
}

</style>